package com.exam.controller;

import com.exam.Result.ApiResult;
import com.exam.Result.ApiResultHandler;
import com.exam.dto.ChangePwdParam;
import com.exam.dto.RegisterParam;
import com.exam.entity.Admin;
import com.exam.entity.Login;
import com.exam.entity.Student;
import com.exam.entity.Teacher;
import com.exam.service.serviceimpl.LoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录控制器
 * 只获取用户数据
 * 校验用户身份交由前端处理
 */
@RestController
public class LoginController {

    @Autowired
    private LoginServiceImpl loginService;

    @PostMapping("/login")
    public ApiResult login(@RequestBody Login login, HttpServletRequest request) {

        String mobile = login.getMobile();
        String password = login.getPassword();
        Admin adminRes = loginService.adminLogin(mobile, password);
        if (adminRes != null) {
            return ApiResultHandler.buildApiResult(200, "请求成功", adminRes);
        }

        Teacher teacherRes = loginService.teacherLogin(mobile,password);
        if (teacherRes != null) {
            return ApiResultHandler.buildApiResult(200, "请求成功", teacherRes);
        }

        Student studentRes = loginService.studentLogin(mobile,password);

        if (studentRes != null) {
            return ApiResultHandler.buildApiResult(200, "请求成功", studentRes);
        }

        return ApiResultHandler.buildApiResult(400, "请求失败", null);
    }


    @PostMapping("/register")
    public ApiResult<String> register(@RequestBody RegisterParam registerParam){
        Integer result = loginService.findById(registerParam.getId());
        if (result!=0){
            return ApiResultHandler.buildApiResult(1,registerParam.getId()+"用户已存在",null);
        }

        return ApiResultHandler.buildApiResult(0,loginService.register(registerParam),registerParam);
    }

    @PostMapping("/changePwd")
    public ApiResult<String> changepd(@RequestBody ChangePwdParam changePwdParam){
        Integer result = loginService.findByPwd(changePwdParam.getId(), changePwdParam.getOldPassword());
        if (result == 0){
            return ApiResultHandler.buildApiResult(1,"原密码错误",null);
        }
        loginService.changePwd(changePwdParam);

        return ApiResultHandler.buildApiResult(0,"修改成功",null);
    }

    @PostMapping("/changePwdTea")
    public ApiResult<String> changePwdTea(@RequestBody ChangePwdParam changePwdParam){
        Integer result = loginService.findByPwdTea(changePwdParam.getId(), changePwdParam.getOldPassword());
        if (result == 0){
            return ApiResultHandler.buildApiResult(1,"原密码错误",null);
        }
        loginService.changePwdTea(changePwdParam);

        return ApiResultHandler.buildApiResult(0,"修改成功",null);
    }


}
